
package petrivis.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import petrivis.view.PNVisualization;

/**
 * Class that Manage all the elements of the IO layer
 * @author Jorge Munoz
 */
public class IOManager {

    /**
     * Save the Petri Net Display compressed in the location's file.
     * @param location Location of the target file
     * @param vis Visualization object to be saved
     * @throws FileNotFoundException if the file exists but is a directory
     * rather than a regular file, does not exist but cannot be created, or
     * cannot be opened for any other reason
     * @throws IOException if an I/O error occurs
     */
    public static void saveVisualization(String location, PNVisualization vis)
            throws FileNotFoundException, IOException{
        
        FileOutputStream fos = new FileOutputStream(location);
        GZIPOutputStream gz = null; //Compress the file
        ObjectOutputStream oos = null;
        try {
            gz = new GZIPOutputStream(fos);
            oos = new ObjectOutputStream(gz);
            oos.writeObject(vis);
            oos.flush();
        } 
        finally{
            if (oos != null) oos.close();
            if (fos != null) fos.close();
        }   
    }

    /**
     * Open a Visualization from a given file
     * @param location Location of the file
     * @return the Visualization opened
     * @throws FileNotFoundException if the file does not exist, is a directory
     * rather than a regular file, or for some other reason cannot be opened for
     * reading.
     * @throws IOException IOException if an I/O error occurs
     * @throws ClassNotFoundException Visualization cannot be found.
     */
    public static PNVisualization openVisualization(String location) 
            throws FileNotFoundException, IOException, ClassNotFoundException{

        FileInputStream fis = new FileInputStream(location);
        GZIPInputStream gs = null; //Compress the file
        ObjectInputStream ois = null;
        try{
            gs = new GZIPInputStream(fis);
            ois = new ObjectInputStream(gs);
            PNVisualization vis = (PNVisualization) ois.readObject();
            return vis;
        }
        finally{
            if (ois != null) ois.close();
            if (fis != null) fis.close();
        }
    }

}
